<!DOCTYPE html>
<html lang="zh-CN">

<head>
  <meta charset="UTF-8">
  <meta name="viewport" content="width=device-width, initial-scale=1.0">
  <title>184_186模态框案例</title>
  <style>
    .modal {
      width: 200px;
      height: 200px;
      background-color: skyblue;
      position: absolute;
      top: 0;
      bottom: 0;
      left: 0;
      right: 0;
      margin: auto;
    }
  </style>
</head>

<body>
  <h1>184_186模态框案例</h1>
  <button id="delete">删除</button>
  <button id="login">登录</button>
  <script>
    function Modal(title, msg) {
      this.modal = document.createElement('div')
      this.modal.className = 'modal'
      this.modal.innerHTML = `
        <div class="header">${title}<i>X</i></div>
        <div class="body">${msg}</div>
      `
    }

    Modal.prototype.open = function () {
      let oModal = document.querySelector('.modal')
      oModal && oModal.remove() // 如果已经存在模态框，就删除，再继续下面的逻辑

      document.body.append(this.modal) // 显示模态框的逻辑就是将模态框节点添加到页面中

      this.modal.querySelector('i').addEventListener('click', () => {
        // 采用普通函数的形式，这里的this指向i标签。
        // 而箭头函数不会创建this，只是沿着作用域链沿用外层的this
        this.close()
      })
    }

    Modal.prototype.close = function () {
      this.modal.remove() // 关闭模态框的逻辑就是将模态框节点移除
    }

    let oDelete = document.querySelector('#delete')
    let oLogin = document.querySelector('#login')

    oDelete.addEventListener('click', function () {
      let del = new Modal('温馨提示', '无删除权限')
      del.open()
    })

    oLogin.addEventListener('click', function () {
      let login = new Modal('温馨提示', '去注册')
      login.open()
    })
  </script>
</body>

</html>